package saleMarket.service;

import saleMarket.dao.CommonDao;
import saleMarket.dao.ShopDao;
import saleMarket.domain.Shop;
import util.JdbcHelper;
import util.exception.ErrorException;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;

public class ShopService {
    private static ShopDao shopDao = ShopDao.getInstance();
    private static ShopService shopService =new ShopService();
    private ShopService(){}

    public static ShopService getInstance(){
        return shopService;
    }

    public Shop find(Integer id) throws SQLException {
        Connection connection= JdbcHelper.getConn();
        Shop result=shopDao.find(id,connection);
        JdbcHelper.close(connection);
        return result;
    }

    public boolean update(Shop shop) throws SQLException {
        Connection connection=JdbcHelper.getConn();
        Boolean result=shopDao.update(shop,connection);
        JdbcHelper.close(connection);
        return result;
    }

    public boolean add(Shop shop) throws SQLException {
        Connection connection=JdbcHelper.getConn();
        Boolean result=shopDao.add(shop,connection);
        System.out.println(shop);
        JdbcHelper.close(connection);
        return result;
    }

    public boolean delete(Integer id)
            throws SQLException,ErrorException {
        Connection connection = JdbcHelper.getConn();
        boolean result=false;
        int countInventoryGoodsOfProfTitle = CommonDao.getInstance().
                countWhereForeignKey(connection,"inventoryGoods","shop_id", id);
        //若没有二级单位，则能够删除
        if(countInventoryGoodsOfProfTitle==0){
            result = shopDao.delete(id,connection);
        }else {
            throw new ErrorException( "有下属系，不能删除");
        }
        JdbcHelper.close(connection);
        return result;
    }
    public Collection<Shop> findAll()
            throws SQLException{
        Connection connection= JdbcHelper.getConn();
        Collection<Shop> shops=shopDao.findAll(connection);
        JdbcHelper.close(connection);

        return shops;
    }
}
